package com.itheima.health.service;

import com.aliyun.oss.ServiceException;
import com.itheima.health.common.R;
import com.itheima.health.mapper.OrdersettingMapper;
import com.itheima.health.model.pojos.ExcelDataBean;
import com.itheima.health.model.pojos.OrderSetting;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class OrdersettingService {
    @Autowired
    private OrdersettingMapper ordersettingMapper;

    public List<OrderSetting> getOrderSettingByMonth(String month) {
        if (month.length()==6){
            String[] split = month.split("-");
            month=split[0]+"-"+"0"+split[1];
        }
        YearMonth parse = YearMonth.parse(month);
        LocalDate firstDay = parse.atDay(1);
        LocalDate lastDay = parse.atEndOfMonth();
        return ordersettingMapper.getOrderSettingByMonth(firstDay,lastDay);

    }


    public R uploadExcel( String fileName,MultipartFile file,R result ) throws Exception {
        try {
            log.debug("开始处理Excel文件！");
            InputStream inputStream = file.getInputStream();
            Workbook wb;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                wb = new XSSFWorkbook(inputStream);
            } else {
                wb = new HSSFWorkbook(inputStream);
            }
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                result.setMessage("Excel数据为空！");
                return result;
            }
            // 列数
            int column = sheet.getRow(0).getPhysicalNumberOfCells();
            log.debug("Excel列数：" + column);
            // 此处可判断Excel列数是否符合要求

            // 行数
            int rows = sheet.getLastRowNum();
            log.debug("Excel行数：" + rows);
            // 此处可判断Excel行数是否符合要求

            List<ExcelDataBean> excelData = new ArrayList<>();
            ExcelDataBean temporary;

            // 循环Excel
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                temporary = new ExcelDataBean();
                // 日期
                if (row.getCell(0) != null) {
                    row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                    String orderDate = row.getCell(0).getStringCellValue();
                    if (orderDate == null || orderDate.isEmpty()) {
                        result.setMessage("Excel中日期称为必填项，不能为空，请填写后再进行上传！");
                        return result;
                    }
                    // Excel基准日期是1900年1月1日
                    LocalDate baseDate = LocalDate.of(1900, 1, 1);

                    // 加上序列号减去1的天数（因为序列号是从1开始）
                    LocalDate actualDate = baseDate.plusDays(Integer.valueOf(orderDate) - 2); // 减去2是因为Excel错误地认为1900年2月29日存在
                    temporary.setOrderDate(actualDate);
                }
                // 预约数量
                if (row.getCell(1) != null) {
                    row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                    String number = row.getCell(1).getStringCellValue();
                    if (number == null || number.isEmpty()) {
                        result.setMessage("Excel中可预约数量为必填项，不能为空，请填写后再进行上传！");
                        return result;
                    }
                    temporary.setNumber(Integer.valueOf(number));
                }
                //添加进list
                excelData.add(temporary);
            }
            // 做插入处理
            if (excelData.size() > 0) {
                // 将Excel数据插入数据库
                int i = ordersettingMapper.insertExcelData(excelData);
                if (i == excelData.size()) {
                    // 数据全部插入成功
                    result.setMessage("success");
                }
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            log.error(">>>>>>>>>>>>>保存Excel数据到数据库【UploadExcelFileServiceImpl.uploadExcel()】执行异常:" + e);
            throw new ServiceException(e.getMessage());
        }
    }
}
